<?php
class CommentsModel extends Model
{
	public $options;
	
	var $_auto = array(
		array('comment_author','fillAuthor','ADD','callback'),
		array('comment_author_IP','get_client_ip','ADD','function'),
		array('comment_author_url','fillAuthorUrl','ADD','callback'),
		array('comment_date','now','ADD','callback'),
		array('comment_approved','checkApprove','ADD','callback'),
		array('comment_type','comment','ADD')
	);

	var $_validate = array(
		array('comment_author','checkName','请填写你的姓名',MUST_TO_VALIDATE,'callback'),
		array('comment_author_email','checkEmail','填写的电子邮箱不正确',MUST_TO_VALIDATE,'callback'),
		array('comment_content','checkLength','评论字数不合要求',MUST_TO_VALIDATE,'callback'),
		array('comment_content','checkIllegal','评论内容含敏感词汇',MUST_TO_VALIDATE,'callback')
	);
	
	function __construct()
	{
		parent::__construct();
		$this->options = S("options"); //先完成基类的构造再加载options的缓存
	}
	
	function now()
	{
		return date("Y-m-d H:i:s");
	}
	
	function checkApprove()
	{
		return $this->options["comment_moderation"]=="open"?"0":"1";
	}

	function fillAuthor()
	{
		$author = trim($_POST["comment_author"]);

		if(!$this->options["require_name_email"] && empty($author))
		{
			//不要求必须填写用户名和邮箱,而且用户没有填写任何用户名
			return "匿名用户";
		}
		else
			return $author; //这一步可不能少,不然自动填充就会出现空值
	}

	function fillAuthorUrl()
	{
		if(strpos($_POST["comment_author_url"],"http") !== 0) //不是以http打头,可能用户只写了域名,帮他补全链接
			$_POST["comment_author_url"] = "http://".$_POST["comment_author_url"];
		if(!preg_match('/^https?:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',$_POST["comment_author_url"]))
			return "";  //不是一个有效的URL,直接过滤掉
		else
			return $_POST["comment_author_url"];
	}
	
	function checkName($author)
	{
		if($this->options["require_name_email"])
		{
			$author = trim($author);
			if(!empty($author))
				return true;
			else
				return false;
		}
		else
			return true;
	}
	
	function checkEmail($email)
	{
		if($this->options["require_name_email"])
		{
			if(preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',trim($email)))
				return true;
			else
				return false;
		}
		else
			return true;
	}

	function checkLength($content)
	{
		return strlen($content)>=$this->options["comment_min_length"] ? true : false;
	}
	
	function checkIllegal($content)
	{
		$keys = explode("\n",str_replace("\r","",$this->options["moderation_keys"]));
		foreach($keys as $key)
		{
			if(strstr($content,$key))
				return false;
		}
		
		return true;
	}
}
?>